package com.feng.cloud.common.handler;

import com.feng.cloud.common.exception.AuthException;
import com.feng.cloud.common.exception.SystemException;
import com.feng.cloud.common.exception.auth.AuthStatus;
import com.feng.cloud.common.exception.system.SystemStatus;
import com.feng.cloud.common.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;


/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常处理器
 * @Author Better Feng
 * @Date 2019/12/19 17:10
 * @Version 1.0
 **/
@RestControllerAdvice("com.feng.cloud")
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse exceptionHandler(Exception e) {
        log.error("系统内部异常，异常信息", e);
        return new BaseResponse(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("系统内部异常");
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public BaseResponse accessDeniedExceptionHandler(AccessDeniedException e) {
        String message = AuthStatus.USER_FORBIDDEN.getMessage();
        log.error(message, e);
        return new BaseResponse(AuthStatus.USER_FORBIDDEN.getStatus()).message(message);
    }

    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse authExceptionHandler(AuthException e) {
        AuthStatus authStatus = e.getAuthStatus();
        log.error(e.getMessage(),e);
        return new BaseResponse(authStatus.getStatus(), authStatus.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse authExceptionHandler(SystemException e) {
        SystemStatus systemStatus = e.getSystemStatus();
        log.error(e.getMessage(),e);
        if (systemStatus != null) {
            return new BaseResponse(systemStatus.getStatus(), systemStatus.getMessage());
        }
        return new BaseResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }
    /**
     * 统一处理请求参数校验(json)
     *
     * @param e ConstraintViolationException
     * @return FebsResponse
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        log.error(message.toString(), e);
        return new BaseResponse(HttpStatus.BAD_REQUEST.value()).message(message.toString());
    }
    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return BaseResponse
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse handleBindException(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return new BaseResponse(HttpStatus.BAD_REQUEST.value()).message(message.toString());
    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return BaseResponse
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
            message.append(pathArr[1]).append(violation.getMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return new BaseResponse(HttpStatus.BAD_REQUEST.value()).message(message.toString());
    }
}
